package com.formula.distribution.encrypt.advice;

import com.formula.distribution.encrypt.annotation.Decrypt;
import com.formula.distribution.encrypt.config.EncryptProperties;
import com.formula.distribution.encrypt.encrypt.AbstractEncrypt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * @author:bo
 * @email:
 * @date 2018/12/15 11:53
 * @introduce
 **/
@Slf4j
@ControllerAdvice
public class EncryptRequestBodyAdvice implements RequestBodyAdvice {


    @Autowired
    EncryptProperties encryptProperties;

    @Autowired
    private AbstractEncrypt abstractEncrypt;


    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {




        if (methodParameter.getMethod().isAnnotationPresent(Decrypt.class) && !encryptProperties.isDebug()) {
            try {
                return new DecryptHttpInputMessage(httpInputMessage, encryptProperties.getKey(), encryptProperties.getCharset(), abstractEncrypt);
            } catch (Exception e) {
                log.error("解密失败", e);
            }
        }

        return httpInputMessage;
    }

    @Override
    public Object afterBodyRead(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {

        return o;
    }

    @Override
    public Object handleEmptyBody(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return o;
    }
}
